var app = angular.module("editEdit", []), weixin_id = UI
		.getParameterByName('weixin_id'), content;

var timeout_json = function(data, $window) {
	if (data.returnCode == 999994) {
		var ss = 3;
		layer.msg(data.returnMessage + "！<strong class='Ajax_Out'>" + ss
				+ "</strong> 秒后前往登录页", 50, -1);
		var picInt = setInterval(function() {
			if (ss >= 1) {
				ss = ss - 1;
				$('.Ajax_Out').text(ss);
			} else {
				clearInterval(picInt);
				try {
					$window.parent.location.href = data.returnData;
					$window.location.href = data.returnData;
				} catch (e) {
					log('timeout!');
				}
			}
		}, 1000);
		return false;
	}
}

app.config(function($httpProvider) {
	$httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded';
	$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
	$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

	$httpProvider.defaults.transformRequest = [ function(data) {
		/**
		 * The workhorse; converts an object to x-www-form-urlencoded
		 * serialization.
		 * 
		 * @param {Object}
		 *            obj
		 * @return {String}
		 */
		var param = function(obj) {
			var query = '';
			var name, value, fullSubName, subName, subValue, innerObj, i;

			for (name in obj) {
				value = obj[name];

				if (value instanceof Array) {
					for (i = 0; i < value.length; ++i) {
						subValue = value[i];
						fullSubName = name + '[' + i + ']';
						innerObj = {};
						innerObj[fullSubName] = subValue;
						query += param(innerObj) + '&';
					}
				} else if (value instanceof Object) {
					for (subName in value) {
						subValue = value[subName];
						fullSubName = name + '[' + subName + ']';
						innerObj = {};
						innerObj[fullSubName] = subValue;
						query += param(innerObj) + '&';
					}
				} else if (value !== undefined && value !== null) {
					query += encodeURIComponent(name) + '='
							+ encodeURIComponent(value) + '&';
				}
			}

			return query.length ? query.substr(0, query.length - 1)
					: query;
		};

		return angular.isObject(data)
				&& String(data) !== '[object File]' ? param(data)
				: data;
	}];
});

var editExaDataLayer = null;
var ruleSelectType = 0;
$('.editExaDataBtn').live('click',function() {
	var editExaDataLayer = $.layer({
		type : 1,
		title : false,
		area : [ '700', 'auto' ],
		border : [ 0 ], // 去掉默认边框
		shade : [ 0.3, '#000' ], // 去掉遮罩
		closeBtn : [ 0, false ], // 去掉默认关闭按钮
		fadeIn : 500,
		move : "#editExaData_tile",
		page : {
			dom : '#editExaDataLayer'
		}
	});
	// 自设关闭
	$('#editExaDataLayer > .closeBtn,#editExaDataLayer .cancelLayer,#editExaSubmitBtn').live('click', function() {
		layer.close(editExaDataLayer);
	});
});
var edit = {
	"qCompanyList" : function(_this, weiboArr, jsons) {
		var _obj = $("#CustomsAreaList");
		var params = {
			pageIndex : 1,
			pageSize : 1000
		}
		$.ajax({
			type : "POST",
			url : basePath + "Tagvalue/queryTagvalue.do?pageIndex="
					+ params.pageIndex + "&pageSize=" + params.pageSize,
			data : params,
			success : function(data) {
				if (data.returnCode == 10000) {
					var s2 = data.returnData.length;
					if (s2 > 0) {
						var htmls = "";
						var checkedHtmls = "";
						for (var i = 0; i < s2; i++) {
							var checkedBtn = "";
							var checked = "";
							var tagvalue_id = data.returnData[i].tagvalue_id;
							var checkeddefault = "";
							var num = weiboArr.length;
							var tf = null;
							for (var nn = 0; nn < num; nn++) {
								if (tagvalue_id == weiboArr[nn]) {
									checkedBtn = "true";
									checked = "checked";
									checkeddefault = "true";
									tf = true;
									break;
								} else {
									checkedBtn = "false";
									checkeddefault = "false";
									checked = "";
									tf = false;
								}
							}
							if (tf == true) {
								checkedHtmls += "<div class='infoLlist' title='"
										+ data.returnData[i].tag_value
										+ "'><span class='ui_checkbox "
										+ checked
										+ "' tagv-id= '"
										+ data.returnData[i].tagvalue_id
										+ "' checkedBtn='"
										+ checkedBtn
										+ "' checkeddefault='"
										+ checkeddefault
										+ "'></span> <font>"
										+ data.returnData[i].tag_type
										+ "-"
										+ data.returnData[i].tag_value
										+ "</font></div>";
							} else if (tf == false) {
								htmls += "<div class='infoLlist' title='"
										+ data.returnData[i].tag_value
										+ "'><span class='ui_checkbox "
										+ checked
										+ "' tagv-id= '"
										+ data.returnData[i].tagvalue_id
										+ "' checkedBtn='"
										+ checkedBtn
										+ "' checkeddefault='"
										+ checkeddefault
										+ "'></span> <font>"
										+ data.returnData[i].tag_type
										+ "-"
										+ data.returnData[i].tag_value
										+ "</font></div>";

							}
						}
						_obj.html(checkedHtmls + htmls
								+ "<div class='clear'></div>");
						checkTrueFalse();
					}
					if (s2 < 1) {
						_obj
								.html("<br><bR><p align='center'>很遗憾，没有查询到相关的数据！</p><br><bR>");
					}
				} else if (data.returnCode == 999994) {
					setUserTimeout(data);
				} else {
					layer.msg(data.returnMessage, 2, -1);
				}
			},
			error : function(message) {
				ayer.msg("操作失败，请重试！", 2, -1);
			},
			beforeSend : function() {
				var imgGif = "<p class='loadingGif'></p>";
				_obj.html(imgGif);
			}
		});
	},
	"quyeryCheck" : function(ids, names) {
		var $selectShowSpan = $(".editExaDataBtn");
		var $showSpan = $selectShowSpan.parent().prev("span");
		$selectShowSpan.attr({
			ids : ids
		});
		$showSpan.attr({
			ids : ids
		});
		$showSpan.text(names);
	}
}
$(".infoLlist .ui_checkbox").live("click", function() {
	if ($(this).attr("checkedBtn") == "true") {
		$(this).attr("checkedBtn", "false");
		$(this).removeClass("checked");
	} else {
		$(this).attr("checkedBtn", "true");
		$(this).addClass("checked");
	}
});
$(".editExaDataBtn").live("mouseover", function() {
	var strId = $(this).attr('ids');
	var weiboArr = strId.split(",");
	ruleSelectType = $(this).attr('type');
	var params = {
		relation_type : ruleSelectType
	};
	edit.qCompanyList($(this), weiboArr, params);
});

$("#tagvalueQueryBtn").live("click", function() {
	publicQDataList3($("#tagvName"));
});
$('.enterKeyDownElement2').keydown(function(e) {
	if (e.keyCode == 13) {
		publicQDataList3($("#tagvName"));
	}
});

function publicQDataList3(_this) {
	var kV = $.trim(_this.val());
	$("#CustomsAreaList .infoLlist").each(function() {
		var name = $(this).children("font").text();
		var isOf = $.trim(name.indexOf(kV));
		if (isOf > -1) {
			$(this).show();
		} else {
			$(this).hide();
		}
	});
}
$("#editExaSubmitBtn").live("click", function() {
	var trueArr = new Array();
	var trueStrArr = new Array();
	$("#CustomsAreaList .ui_checkbox").each(function() {
		var id = $(this).attr("tagv-id");
		var name = $(this).next("font").text();
		var checkedbtn = $(this).attr("checkedbtn");
		var checkeddefault = $(this).attr("checkeddefault");
		if (checkedbtn == "true") {
			trueArr.push(id);
			trueStrArr.push(name);
		}
		;
	});
	var trueArrs = "";
	var trueStrArrs = "";
	if (trueArr.length > 0) {
		trueArrs = trueArr.join(",");
		trueStrArrs = trueStrArr.join(",");
	}
	edit.quyeryCheck(trueArrs, trueStrArrs);
	$(".xubox_main").css("cssText", "height:45px!important; z-index:198916;");
});

$(".selectAllAreaGoGo .allSel").live(
		"click",
		function() {
			var checkedbtn = $(this).attr("checkedbtn");
			if (checkedbtn == "true") {
				$("#CustomsAreaList .infoLlist .ui_checkbox").addClass(
						"checked").attr("checkedbtn", "true");
			} else {
				$("#CustomsAreaList .infoLlist .ui_checkbox").removeClass(
						"checked").attr("checkedbtn", "false");
			}
		});

$(".selectAllAreaGoGo .reDefault").live("click", function() {
	$("#CustomsAreaList .infoLlist .ui_checkbox").each(function() {
		var checkeddefault = $(this).attr("checkeddefault");
		if (checkeddefault == "true") {
			$(this).addClass("checked").attr("checkedbtn", "true");
		} else {
			$(this).removeClass("checked").attr("checkedbtn", "false");
		}
	});
	checkTrueFalse();
});
$("#CustomsAreaList .infoLlist .ui_checkbox").live("click", function() {
	checkTrueFalse();
});

function checkTrueFalse() {
	var isTrue = "true";
	$("#CustomsAreaList .infoLlist .ui_checkbox").each(function() {
		var checkedbtn = $(this).attr("checkedbtn");
		if (checkedbtn == "false") {
			isTrue = "false";
			return;
		}
	});
	if (isTrue == "false") {
		$(".selectAllAreaGoGo .allSel").removeClass("checked").attr(
				"checkedbtn", "false");
	} else {
		$(".selectAllAreaGoGo .allSel").addClass("checked").attr("checkedbtn",
				"true");
	}
}

app.controller('editCtrl', function($scope, $http, $window, $timeout) {
	// 查询到的数据显示到修改页面上
	$http.post(basePath + 'weixin/queryWeixinById.do?weixin_id=' + weixin_id)
			.success(function(data) {
				content = $scope.content = data.returnData;
				// 标签
				if (content.list != null && content.list != undefined) {
					var list = content.list;
					var arr1 = new Array();
					var arr2 = new Array();
					var arr3 = new Array();
					$scope.content.tag_value = "";
					$scope.content.tag_type = "";
					$scope.content.tagvalue_id = "";
					$.each(list, function(i, n) {
						arr1.push(n.tag_value);
						arr2.push(n.tag_type);
						arr3.push(n.tagvalue_id);
					});
					if (arr1.length > 0) {
						$scope.content.tag_value = arr1.join(",");
						$scope.content.tag_type = arr2.join(",");
						$scope.content.tagvalue_id = arr3.join(",");
					}
				}
			});
	// 点击取消 关闭窗口
	$scope.close = function(e) {
		window.parent.layer.closeAll();
	}
	var avoidDup = true;
	// 修改
	$scope.domAjax = function(e) {
		var ids = $(".editExaDataBtn").attr('ids');

		var params = {
			weixinuser_Id : content.weixinuser_Id,
			weixin_name : content.weixin_name,
			tagvalue_id : ids,
			weixin_id : weixin_id
		};
		if(content.weixinuser_Id!=null&&content.weixin_name!=null){
			if (e == "save") {
				if(avoidDup==false){
					return false;
				}
				var urls = "weixin/modifyWeixin.do";
				avoidDup =false;
				$.ajax({
					type : "post",
					url : basePath + urls,
					data : params,
					error : function(request) {
						layer.msg("操作失败，请重试", 2, -1);
					},
					success : function(data) {
						var j = timeout_json(data, $window);
						if (j == false) {
							return false;
						}
						if (data.returnCode == 10000) {
							layer.msg(data.returnMessage, 1, 10);
							$timeout(function(){
								try {
									window.parent.$(".dtab").find('#jsgo a.cur').trigger('click');
								} catch(e) {}
								window.parent.layer.closeAll();
							},1000);
						} else {
							layer.msg(data.returnMessage, 2, -1);
							avoidDup = true;
							return false;
						}
					}
				});
			}
		}
	}
});
